package com.apestech.framework.run.core;

import java.util.Vector;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.apestech.framework.run.callback.ParamThreadCallBack;
import com.apestech.framework.run.callback.ThreadCallBackHandler;
import com.apestech.framework.run.modul.ListParam;
import com.apestech.framework.run.modul.MutiParam;
import com.apestech.framework.run.modul.RunInfo;
import com.apestech.framework.run.modul.SingleParam;
import com.apestech.framework.util.ReflectUtil;

public class ThreadPool {
	
	private ThreadPoolExecutor executor=null; 
	private Vector<SingleThread> taskList=new Vector<SingleThread>();
	private Vector<RunInfo> runInfoList=new Vector<RunInfo>();;
	
	public ThreadPool(){
	}
	
    public void clearTask(){
		this.taskList.clear();
		this.runInfoList.clear();
	}
	
    public void beginRun(){
    	clearTask();
    	this.executor=null;
    }
    
    public void run(Vector<SingleThread> list){
    	int len=list.size();
    	for(int i=0; i<len; i++){
    		run(list.get(i));
    	}
    }
    
    public void run(SingleThread run){
    	this.taskList.add(run);
    	if(this.executor==null){
    		this.executor= new ThreadPoolExecutor(5, 10, 1000, TimeUnit.MILLISECONDS,
    	            new ArrayBlockingQueue<Runnable>(5));
    	}
    	this.executor.execute(run);
    	System.out.println("线程池中线程数目："+this.executor.getPoolSize()+
		           "，队列中等待执行的任务数目："+this.executor.getQueue().size()+
		           "，已执行完别的任务数目："+executor.getCompletedTaskCount());
    }
    
    public void shutdown(){
    	executor.shutdown();
    	while(executor.getActiveCount()!=0){};
    	executor=null;
    	int len=this.taskList.size();
    	for(int i=0; i<len; i++){
    		SingleThread thread=this.taskList.get(i);
    		RunInfo info=new RunInfo(thread.getName(), thread.getRunTime(), 
    				thread.getCostTime(), thread.getErrorMsg());
    		this.runInfoList.add(info);
    	}
    }
    
    public String toString(){
    	StringBuilder sb=new StringBuilder();
    	int len=this.runInfoList.size();
    	for(int i=0; i<len; i++){
    		sb.append(this.runInfoList.get(i).toString()+"\r\n");
    	}
    	return sb.toString();
    }
    
    public Vector<RunInfo> getRunInfo(){
    	return this.runInfoList;
    }

}
